﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using ConfigInfoWebPlatform.Nlog;
using ConfigInfoWebPlatform.API.DBCommon;
using FileSecretAssemblyStandard;
using Microsoft.Extensions.Configuration;
using System.IO;
using ConfigInfoWebPlatform.Model;
using System.Xml;
using ConfigInfoWebPlatform.API.ViewModel;
using ConfigInfoWebPlatform.Model.Model;
using System.Text;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using ConfigInfoWebPlatform.API.BusinessCommon;
using ConfigInfoWebPlatform.API.HubMessage;

namespace ConfigInfoWebPlatform.API.Controllers
{
    /// <summary>
    /// 公共配置文件控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class CommonConfigController : ControllerBase
    {
        readonly LogHelper _log;
        readonly string configRootPath;
        readonly string initDB;
        readonly InterfaceFileSecret FileSecret;
        readonly HubMessageServer hubMessageServer;
        private string backupRootPath;

        /// <summary>
        /// 公共配置文件控制器
        /// </summary>
        /// <param name="logHelper"></param>
        /// <param name="configuration"></param>
        /// <param name="fileSecret"></param>
        public CommonConfigController(LogHelper logHelper, IConfiguration configuration, InterfaceFileSecret fileSecret,HubMessageServer hubMessage)
        {
            _log = logHelper;
            configRootPath = configuration["AppSetting:configPath"].ToString();
            backupRootPath = configRootPath.Replace("wordparse2.0", "备份");
            initDB = configuration["AppSetting:initDB"].ToString();
            FileSecret = fileSecret;
            hubMessageServer = hubMessage;
        }

        /// <summary>
        /// 获取公共配置目录数据
        /// </summary>
        [HttpGet("getcommonconfigcatalogue")]
        public JsonResult GetCommonConfigCatalogue(string dir)
        {
            //获取用户信息
            UserInfoModel user = new UserInfoModel();
            var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
            user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);
            DAL_UserInfo userDal = new DAL_UserInfo();
            string rid = userDal.GetUserRid(user.Id);
            //获取版本信息
            VersionModel version = new VersionModel();
            var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
            version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
            var versionPath = version?.Catalogue == "dev"
                           ? ""
                           : version?.Catalogue;

            if (!Directory.Exists(Path.Combine(configRootPath, versionPath , dir)))
            {
                Directory.CreateDirectory(Path.Combine(configRootPath, versionPath , dir));
            }
            List<CatalogueTreeModel> catalogueList = new List<CatalogueTreeModel>();
            CatalogueTreeModel root = new CatalogueTreeModel();
            GetCatalogueTree(dir,configRootPath.Replace("\\","/"), versionPath, root);
            catalogueList.Add(root);
            return new JsonResult(new { code = 0, msg = "成功", data = catalogueList });
        }

        /// <summary>
        /// 获取公共配置文件数据
        /// </summary>
        [HttpGet("getcommonconfigfile")]
        public JsonResult GetCommonConfigFile(string dir,string fileName, int page,int limit)
        {
            //获取用户信息
            UserInfoModel user = new UserInfoModel();
            var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
            user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);
            //获取用户角色操作权限
            DAL_Role dal_Role = new DAL_Role();
            var isOperate = dal_Role.GetOperateAuthorityByRid(user.R_id);
            //获取版本信息
            VersionModel version = new VersionModel();
            var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
            version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
            //公共配置文件列表
            List<CommonConfigFileInfoModel> commonConfigFileList  = new List<CommonConfigFileInfoModel>();
            var versionPath = version?.Catalogue == "dev"
                           ? ""
                           : version?.Catalogue;

            if (!Directory.Exists(Path.Combine(configRootPath, versionPath, dir)))
            {
                Directory.CreateDirectory(Path.Combine(configRootPath, versionPath, dir));
            }
            DirectoryInfo folder = new DirectoryInfo(Path.Combine(configRootPath, versionPath, dir));
            FileInfo[] files = folder.GetFiles();
            if (!string.IsNullOrWhiteSpace(fileName))
            {
                files = files.Where(x => x.Name.ToLower().Contains(fileName.ToLower())).ToArray();
            }
            // 遍历当前目录下的文件，将文件信息存入到配置文件模型中
            foreach (FileInfo file in files)
            {
                if (file.Extension == ".xml" || file.Extension == ".txt" || file.Extension == ".json")
                {
                    CommonConfigFileInfoModel fileInfo = new CommonConfigFileInfoModel();
                    fileInfo.name = file.Name;
                    fileInfo.path = file.FullName.Replace(configRootPath + "\\", "").Replace("\\", "/");
                    fileInfo.parentPath = dir;
                    fileInfo.fileSize = file.Length.ToString() + "B";
                    fileInfo.updateTime = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                    fileInfo.createdTime = file.CreationTime.ToString("yyyy-MM-dd HH:mm:ss");
                    string explain = "";
                    if (file.Extension == ".xml")
                    {
                        XmlDocument xmlDocument = new XmlDocument();
                        try
                        {
                            xmlDocument.Load(folder + @"\" + file.Name);
                            if (xmlDocument.SelectNodes("root").Count > 0 && xmlDocument.SelectNodes("root")[0].Attributes["explain"] != null)
                            {
                                explain = xmlDocument.SelectNodes("root")[0].Attributes["explain"].Value;
                            }
                        }
                        catch (Exception ex)
                        {
                            explain = "";
                        }
                    }
                    fileInfo.note = explain;
                    commonConfigFileList.Add(fileInfo);
                }
            }
            int taotalcount = 0;
            if (commonConfigFileList.Any())
            {
                taotalcount = commonConfigFileList.Count;
                commonConfigFileList = commonConfigFileList.Skip((page - 1) * limit).Take(limit).ToList();
            }
            CommonConfigFileJsonObject jsonResult = new CommonConfigFileJsonObject();
            jsonResult.code = 0;
            jsonResult.msg = "success";
            jsonResult.count = taotalcount;
            jsonResult.data = commonConfigFileList;
            jsonResult.isOperate = user.Name == "admin" ? 1 : isOperate;
            return new JsonResult(jsonResult);
        }

        /// <summary>
        /// 获取公共配置树
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        [HttpGet("getcommonconfigtree")]
        public JsonResult GetCommonConfigTree()
        {
            //获取用户信息
            UserInfoModel user = new UserInfoModel();
            var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
            user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);
            //获取版本信息
            VersionModel version = new VersionModel();
            var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
            version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);

            string commonCofigPath = @"config/moduleconfig/commonconfig";

            var versionPath =( version?.Catalogue == "dev" || string.IsNullOrWhiteSpace(version?.Catalogue))
                           ? ""
                           : version?.Catalogue;

            if (!Directory.Exists(Path.Combine(configRootPath, versionPath, commonCofigPath)))
            {
                Directory.CreateDirectory(Path.Combine(configRootPath, versionPath, commonCofigPath));
            }
            List<CommonConfigTreeModel> treeList = new List<CommonConfigTreeModel>();
            CommonConfigTreeModel root = new CommonConfigTreeModel();
            GetFiles(commonCofigPath, configRootPath.Replace("\\","/"), versionPath, root);
            treeList.Add(root);
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;

            var result = new
            {
                code = 0,
                msg = "成功",
                data = treeList
            };
            return new JsonResult(result);
        }

        /// <summary>
        /// 添加目录
        /// </summary>
        [HttpPost("addcatalogue")]
        public JsonResult AddCatalogue([FromBody]CatalogueSubmitModel model)
        {
            try
            {
                //获取用户信息
                UserInfoModel user = new UserInfoModel();
                var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
                user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);
                DAL_UserInfo userDal = new DAL_UserInfo();
                string rid = userDal.GetUserRid(user.Id);
                //获取版本信息
                VersionModel version = new VersionModel();
                var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
                version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
                var resultMsg = string.Empty;
                var versionPath = version?.Catalogue == "dev"
                                ? ""
                                : version?.Catalogue;
                var fullPath = Path.Combine(configRootPath, versionPath, model.ParentPath, model.Name.ToLower());
                
                if (!Directory.Exists(fullPath))
                {
                    DAL_ConfigFile dAL_ConfigFile = new DAL_ConfigFile();
                    Directory.CreateDirectory(fullPath);
                    string currentId = System.Guid.NewGuid().ToString("N");
                    var parentConfig = dAL_ConfigFile.GetConfigFileByPath(model.ParentPath);
                    ConfigFiles configFile = new ConfigFiles();
                    configFile.Currentid = currentId;
                    configFile.Programid = parentConfig.Programid;
                    configFile.Parentid = parentConfig.Currentid;
                    configFile.Level = parentConfig.Level + 1;
                    configFile.Name = model.Name.ToLower();
                    configFile.Ctype = "D";
                    configFile.Path = $"{parentConfig.Path}/{model.Name.ToLower()}";
                    configFile.ParentPath = model.ParentPath;
                    configFile.Filesize =string.Empty;
                    configFile.Createdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    configFile.Updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    configFile.Status = "1";
                    configFile.Note = string.Empty;
                    dAL_ConfigFile.InsertConfig(configFile);
                    #region 更新菜单统计数量
                    DAL_ProgramNavicat navicatDal = new DAL_ProgramNavicat();
                    var nav = navicatDal.GetNavicatById(parentConfig.Programid.Value);
                    if (nav != null)
                    {
                        DAL_MenuStatistics statisticsDal = new DAL_MenuStatistics();
                        //修改当前菜单文件数量
                        statisticsDal.FloderNumIncremental(nav.Id);

                        //修改父级菜单文件数量
                        var allParentId = nav.AllParentId;
                        if (!string.IsNullOrWhiteSpace(allParentId))
                        {
                            List<string> parentids = allParentId.Split(",").Reverse().ToList();
                            foreach (var id in parentids)
                            {
                                long navId = Int64.Parse(id);
                                statisticsDal.FloderNumIncremental(navId);
                            }
                        }
                    }
                    #endregion
                    RefreshStatistics(user.Name, rid);
                    resultMsg = "添加目录成功";
                }
                else
                {
                    resultMsg = "该目录已存在";
                }
                return new JsonResult(new { code = 0, msg = resultMsg });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { code = 0, msg = ex.Message });
            }         
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns>上传文件结果信息</returns>
        [HttpPost("uploadfile")]
        public ActionResult UploadFile(string dir)
        {
            //获取用户信息
            UserInfoModel user = new UserInfoModel();
            var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
            user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);
            DAL_UserInfo userDal = new DAL_UserInfo();
            string rid = userDal.GetUserRid(user.Id);
            //获取版本信息
            VersionModel version = new VersionModel();
            var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
            version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
            var versionPath = version?.Catalogue == "dev"
                                ? ""
                                : version?.Catalogue;
            Result re = new Result();
            // 上传文件中，faildFiles表示上传失败的文件名，successFiles表示上传成功的文件名
            List<string> faildFiles = new List<string>();
            List<string> successFiles = new List<string>();
            // 上传失败的数量
            int failedNum = 0;
            try
            {
                var files = Request.Form.Files;
                dir = Request.Form["dir"].ToString();
                string fileParentdir = dir.Replace("\\", "/");
                string describe = "";
                for (int i = 0; i < files.Count; i++)
                {
                    _log.WriteLog(LogHelper.logType.Debug, "CommonConfigController-UploadFile方法：上传的文件是" + files[i].FileName);
                    string filename = Path.GetFileName(files[i].FileName);
                    string fileParentPath = fileParentdir;
                    string fullpath = Path.Combine(configRootPath, versionPath, fileParentPath, "_" + filename);
                    string absolutePath = Path.Combine(configRootPath, versionPath, fileParentPath, filename).Replace("\\", "/");
                    string backPath = Path.Combine(backupRootPath, versionPath, fileParentPath, filename).Replace("\\", "/");
                    if (System.IO.File.Exists(absolutePath))
                    {
                        _log.WriteLog(LogHelper.logType.Debug, "CommonConfigController-UploadFile方法：上传的文件" + filename + "已经存在！");
                        // 这里要判断一下是否文件的后缀名，如果是dll，要删除旧文件，保存新文件；同时要在dlls文件夹下创建新的版本目录
                        string extensionName = Path.GetExtension(fullpath);
                        if (extensionName == ".dll")
                        {
                            // 删除模块下旧的文件，保存新的文件
                            System.IO.File.Delete(fullpath);
                            FileStream fileStream = new FileStream(fullpath, FileMode.CreateNew);
                            files[i].CopyTo(fileStream);
                            fileStream.Close();
                            //files[i].SaveAs(filename);
                            // 拼接成dll各个版本的存储目录
                            try
                            {
                                // 应用目录
                                DirectoryInfo appDir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
                                string fileN = Path.GetFileName(fullpath);
                                string rootPath = !string.IsNullOrWhiteSpace(versionPath) ? $"{configRootPath}/{versionPath}" : configRootPath;
                                string dllPath = rootPath+ @"/config/dlls/" + fileN.Substring(0, fileN.Length - 4);
                                // 生成新的版本文件
                                string versionNo = DateTime.Now.ToString("yyyyMMddHHmmss");
                                Directory.CreateDirectory(Path.Combine(dllPath, versionNo));
                                System.IO.File.Copy(filename, Path.Combine(dllPath, versionNo, Path.GetFileName(fullpath)));
                                // 根据描述信息生成描述文件
                                CreateDescribeFile(dllPath, versionNo, describe);
                                successFiles.Add(filename);
                                _log.WriteLog(LogHelper.logType.Info, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}用户{user.Name}在{fileParentPath}下上传文件{Path.GetFileName(files[i].FileName)}");
                            }
                            catch (Exception ex)
                            {
                                _log.WriteLog(LogHelper.logType.Error, "CommonConfigController-UploadFile方法：" + fullpath + "上传失败!错误信息" + ex.Message);
                            }
                        }
                        else
                        {
                            FileInfo fi = new FileInfo(absolutePath);
                            if (!Directory.Exists(Path.GetDirectoryName(backPath)))
                                Directory.CreateDirectory(Path.GetDirectoryName(backPath));
                            fi.MoveTo(backPath + "back" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                            FileStream fileStream = new FileStream(fullpath, FileMode.CreateNew);
                            files[i].CopyTo(fileStream);
                            fileStream.Close();
                            this.EncryptFileToFile(fullpath, absolutePath);
                            _log.WriteLog(LogHelper.logType.Info, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}用户{user.Name}在{fileParentPath}下替换文件{Path.GetFileName(files[i].FileName)}");
                            System.IO.File.Delete(fullpath);
                            successFiles.Add(filename);
                            SaveFileInfoToDb(absolutePath, fileParentPath, filename, describe);
                        }
                    }
                    else
                    {
                        //文件相对路径
                        string fileRelativePath = fileParentPath;

                        FileStream fileStream = new FileStream(fullpath, FileMode.CreateNew);
                        files[i].CopyTo(fileStream);
                        fileStream.Close();
                        //files[i].SaveAs(filename);
                        var enfilename = Path.Combine(configRootPath, versionPath, fileParentPath, filename).Replace("\\", "/");
                        this.EncryptFileToFile(fullpath, enfilename);
                        string versionNo = DateTime.Now.ToString("yyyyMMddHHmmss");
                        string extensionName = Path.GetExtension(fullpath);
                        if (extensionName == ".dll")
                        {
                            string fileN = Path.GetFileName(fullpath);
                            string rootPath = !string.IsNullOrWhiteSpace(versionPath) ? $"{configRootPath}/{versionPath}" : configRootPath;
                            string dllPath = rootPath + @"/config/dlls/" + fileN.Substring(0, fileN.Length - 4);
                            // 首次上传生成版本目录

                            Directory.CreateDirectory(Path.Combine(dllPath, versionNo));
                            System.IO.File.Copy(fullpath, Path.Combine(dllPath, versionNo, Path.GetFileName(fullpath)));
                            // 根据描述信息生成描述文件
                            CreateDescribeFile(dllPath, versionNo, describe);
                        }

                        _log.WriteLog(LogHelper.logType.Debug, "MoudleCfgController-UploadFile方法：" + fullpath + "上传成功!");
                        _log.WriteLog(LogHelper.logType.Info, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}用户{user.Name}在{fileParentPath}下上传文件{filename}");
                        successFiles.Add(filename);
                        System.IO.File.Delete(fullpath);
                        SaveFileInfoToDb(enfilename, fileParentPath, filename, describe);
                    }

                }
                RefreshStatistics(user.Name, rid);
                var failMsg = faildFiles.Count > 0
                            ? $"{string.Join(",", faildFiles)}上传失败"
                            : string.Empty;
                var successMsg = successFiles.Count>0
                               ?$"{string.Join(",", successFiles)}上传成功"
                               :string.Empty;
                re.message = faildFiles.Count > 0
                           ? failMsg + Environment.NewLine + successMsg
                           : successMsg;
                re.code = "1";
            }
            catch (Exception e)
            {
                _log.WriteLog(LogHelper.logType.Error, "MoudleCfgController-UploadFile方法：出现异常" + e.Message);
                re.code = "0";
                re.message = e.Message;
            }

            return new JsonResult(re);
        }

        /// <summary>
        /// 查看文件内容
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <returns></returns>
        [HttpGet("detail")]
        public ActionResult Detail(string fileName)
        {
            //获取用户信息
            UserInfoModel user = new UserInfoModel();
            var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
            user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);
            //获取版本信息
            VersionModel version = new VersionModel();
            var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
            version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
            var versionPath = version?.Catalogue == "dev"
                                ? ""
                                : version?.Catalogue;
            string fileContent = "";
            try
            {
                string filenametemp = Path.Combine(configRootPath,versionPath ,fileName);
                fileContent = FileSecret.DecryptFileToContent(filenametemp);
                return new JsonResult(fileContent);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        [HttpGet("downloadfile")]
        public ActionResult DownLoadFile(string fileName)
        {
            //获取用户信息
            UserInfoModel user = new UserInfoModel();
            var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
            user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);
            //获取版本信息
            VersionModel version = new VersionModel();
            var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
            version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
            var versionPath = version?.Catalogue == "dev"
                                ? ""
                                : version?.Catalogue;
            Result re = new Result();
            if (!string.IsNullOrEmpty(fileName))
            {
                re.code = "1";
                string filenameTemp = Path.Combine(configRootPath, versionPath,fileName);
                string clientFileName = Path.GetFileName(fileName);
                string fileContent = FileSecret.DecryptFileToContent(filenameTemp);
                byte[] bytes = Encoding.UTF8.GetBytes(fileContent);
                //二进制流数据（如常见的文件下载）
                return File(bytes, "application/octet-stream", clientFileName);
            }
            else
            {
                re.code = "0";
                re.message = "下载失败";
                return BadRequest(re);
            }
        }

        /// <summary>
        /// 删除配置文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        [HttpPost("delfile")]
        public ActionResult DelFile(string fileName)
        {
            //获取用户信息
            UserInfoModel user = new UserInfoModel();
            var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
            user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);
            DAL_UserInfo userDal = new DAL_UserInfo();
            string rid = userDal.GetUserRid(user.Id);
            //获取版本信息
            VersionModel version = new VersionModel();
            var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
            version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
            var versionPath = version?.Catalogue == "dev"
                                ? ""
                                : version?.Catalogue;
            string fileNameFull = Path.Combine(configRootPath,versionPath ,fileName);
            string backPath = Path.Combine(backupRootPath, versionPath, fileName);
            if (!Directory.Exists(Path.GetDirectoryName(backPath)))
                Directory.CreateDirectory(Path.GetDirectoryName(backPath));
            // 对要删除的文件重命名
            FileInfo fi = new FileInfo(fileNameFull);
            fi.MoveTo(backPath + "back" + DateTime.Now.ToString("yyyyMMddHHmmss"));
            _log.WriteLog(LogHelper.logType.Debug, "CommonConfigController-DelFile方法：删除" + fileName + "文件！系统将该文将重命名为" + fileName + "back" + DateTime.Now.ToString("yyyyMMddHHmmss"));
            // 数据中删除该文件的记录
            fileName = fileName.Replace("\\", "/");
            _log.WriteLog(LogHelper.logType.Debug, "CommonConfigController-DelFile方法：删除文件" + fileName + "数据库记录");
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            DAL_ProgramNavicat navicatDal = new DAL_ProgramNavicat();
            var configFileInfo = configFileDal.GetConfigFileByPath(fileName);
            if (configFileDal.ExistFile(fileName) > 0)
            {
                configFileDal.DeleteConfigFile(fileName);
                var nav = navicatDal.GetNavicatById(configFileInfo.Programid.Value);
                if (nav != null)
                {
                    DAL_MenuStatistics statisticsDal = new DAL_MenuStatistics();
                    //修改当前菜单文件数量
                    statisticsDal.FileNumDecrement(nav.Id);

                    //修改父级菜单文件数量
                    var allParentId = nav.AllParentId;
                    if (!string.IsNullOrWhiteSpace(allParentId))
                    {
                        List<string> parentids = allParentId.Split(",").Reverse().ToList();
                        foreach (var id in parentids)
                        {
                            long navId = Int64.Parse(id);
                            statisticsDal.FileNumDecrement(navId);
                        }
                    }
                }
            }
            RefreshStatistics(user.Name, rid);
            return new JsonResult(new { code = 1, msg = "删除成功" });
        }

        /// <summary>
        /// 上传dll时生成描述文件
        /// </summary>
        /// <param name="dllPath">dll文件保存的路径</param>
        /// <param name="versionNo">dll版本目录</param>
        /// <param name="describe">描述性内容</param>
        private void CreateDescribeFile(string dllPath, string versionNo, string describe)
        {
            // 如果没有描述性说明就不生成描述文件
            if (describe.Length > 0)
            {
                string desFile = dllPath + @"\" + versionNo + @"\describe.txt";
                if (System.IO.File.Exists(desFile))
                {
                    StreamWriter streamWriter = System.IO.File.AppendText(desFile);
                    streamWriter.WriteLine(describe);
                    streamWriter.Close();
                }
                else
                {
                    FileStream fileStream = new FileStream(desFile, FileMode.Create, FileAccess.Write);
                    StreamWriter streamWriter = new StreamWriter(fileStream);
                    streamWriter.WriteLine(describe);
                    streamWriter.Close();
                }
            }
        }

        /// <summary>
        /// 加密文件，输入源文件路径返回加密后文件路径
        /// </summary>
        /// <param name="inFileName">明文文件路径</param>
        /// <param name="outFileName">密文文件路径</param>
        private void EncryptFileToFile(string inFileName, string outFileName)
        {
            if (inFileName == outFileName)
            {
                string enFileName = Path.GetDirectoryName(inFileName) + "_" + Path.GetFileName(inFileName);
                FileSecret.EncryptFile(inFileName, enFileName);
                System.IO.File.Delete(inFileName);
                System.IO.File.Copy(enFileName, inFileName);
                System.IO.File.Delete(enFileName);
            }
            else
            {
                FileSecret.EncryptFile(inFileName, outFileName);
            }
        }

        /// <summary>
        /// 递归获取目录树
        /// </summary>
        private void GetCatalogueTree(string dirPath,string rootPath,string versionPath ,CatalogueTreeModel catalogue)
        {
            try
            {
                DAL_ConfigFile dAL_ConfigFile = new DAL_ConfigFile();
                DirectoryInfo folder = new DirectoryInfo(Path.Combine(rootPath, versionPath,dirPath));
                catalogue.title = folder.Name;
                var parentPath = !string.IsNullOrWhiteSpace(versionPath)
                                        ? $"{rootPath}/{versionPath}/"
                                        : $"{rootPath}/";
                var dirRelativePath= folder.FullName.Replace("\\", "/").Replace(parentPath, "");
                var dirParentPath = folder.Parent.FullName.Replace("\\", "/").Replace(parentPath, "");
                catalogue.href = dirRelativePath;
                if (catalogue.childrens == null)
                    catalogue.childrens = new List<CatalogueTreeModel>();
                DirectoryInfo[] childs = folder.GetDirectories();
                
                foreach (DirectoryInfo child in childs)
                {
                    CatalogueTreeModel children = new CatalogueTreeModel();
                    children.title = child.Name;
                    var relativePath = child.FullName.Replace("\\", "/").Replace(parentPath, "");
                    children.href =relativePath ;
                    catalogue.childrens.Add(children);
                    GetCatalogueTree(child.FullName, rootPath,versionPath ,children);
                }
            }
            catch (Exception ex)
            {
                var str = ex.Message;
            } 
        }

        private void GetFiles(string filePath,string rootPath,string versionPath ,CommonConfigTreeModel root)
        {
            DirectoryInfo dir = new DirectoryInfo(Path.Combine(rootPath,versionPath, filePath));
            root.Name = dir.Name;
            root.FullName = dir.FullName;
            root.NoteType = "D";
            root.Id = dir.Name;
            if (root.children == null)
                root.children = new List<CommonConfigTreeModel>();
            FileInfo[] chldFiles = dir.GetFiles("*.*");
            var parentPath = string.IsNullOrWhiteSpace(versionPath)
                           ? rootPath
                           : $"{rootPath}/{versionPath}";
            foreach (FileInfo chlFile in chldFiles)
            {
                if (!string.IsNullOrWhiteSpace(chlFile.Extension) && !chlFile.Extension.ToLower().Contains("back"))
                {
                    CommonConfigTreeModel fileNode = new CommonConfigTreeModel();
                    fileNode.Name = chlFile.Name;
                    fileNode.FullName = chlFile.FullName.Replace("\\", "/").Replace(parentPath + "/", "");
                    fileNode.NoteType = "F";
                    fileNode.Id = chlFile.Name;
                    root.children.Add(fileNode);
                }
            }

            DirectoryInfo[] chldFolders = dir.GetDirectories();
            foreach (DirectoryInfo chldFolder in chldFolders)
            {
                CommonConfigTreeModel chldNode = new CommonConfigTreeModel();
                chldNode.Name = chldFolder.Name;
                chldNode.FullName = chldFolder.FullName.Replace("\\", "/").Replace(parentPath + "/", "");
                chldNode.NoteType ="D";
                chldNode.Id = chldFolder.Name;
                root.children.Add(chldNode);
                GetFiles(chldFolder.FullName, rootPath,versionPath ,chldNode);
            }
        }

        /// <summary>
        /// 将文件信息存储到数据库中
        /// </summary>
        /// <param name="fullPath">文件路径</param>
        /// <param name="fileParentPath">文件路径</param>
        /// <param name="fileName">文件路径</param>
        /// <param name="explain">文件备注</param>
        private void SaveFileInfoToDb(string fullPath, string fileParentPath, string fileName, string explain)
        {
            DAL_ConfigFile dAL_ConfigFile = new DAL_ConfigFile();
            // 获取导航功能ID
            string configPath = fileParentPath.Replace("\\",@"/");
            //string configPath = Path.GetDirectoryName(fileParentPath);
            DAL_ProgramNavicat navicatDal = new DAL_ProgramNavicat();
            var programid = navicatDal.GetProgramId(configPath);
            // 现判断该文件是否存在
            string fileRelativePath = Path.Combine(fileParentPath, fileName).Replace("\\", @"/");
            int re = dAL_ConfigFile.ExistFile(fileRelativePath);
            if (re <= 0)
            {
                FileInfo fileInfo = new FileInfo(fullPath);
                string currentId = System.Guid.NewGuid().ToString("N");
                var parentConfig = dAL_ConfigFile.GetConfigFileByPath(configPath);
                ConfigFiles model = new ConfigFiles();
                model.Currentid = currentId;
                model.Programid = programid;
                model.Parentid = parentConfig.Currentid;
                model.Level = parentConfig.Level + 1;
                model.Name = fileInfo.Name;
                model.Ctype = "F";
                model.Path = fileRelativePath;
                model.ParentPath = configPath;
                model.Filesize = fileInfo.Length.ToString() + "B";
                model.Createdtime = fileInfo.CreationTime.ToString("yyyy-MM-dd HH:mm:ss");
                model.Updatetime = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                model.Status = "1";
                model.Note = explain;
                dAL_ConfigFile.InsertConfig(model);
                #region 更新菜单统计数量
                var nav = navicatDal.GetNavicatById(programid);
                if (nav != null)
                {
                    DAL_MenuStatistics statisticsDal = new DAL_MenuStatistics();
                    //修改当前菜单文件数量
                    statisticsDal.FileNumIncremental(nav.Id);

                    //修改父级菜单文件数量
                    var allParentId = nav.AllParentId;
                    if (!string.IsNullOrWhiteSpace(allParentId))
                    {
                        List<string> parentids = allParentId.Split(",").Reverse().ToList();
                        foreach (var id in parentids)
                        {
                            long navId = Int64.Parse(id);
                            statisticsDal.FileNumIncremental(navId);
                        }
                    }
                }
                #endregion
            }
            else
            {
                dAL_ConfigFile.UpdateStamp(fileRelativePath);
            }
        }

        /// <summary>
        /// 刷新配置文件统计数量
        /// </summary>
        private void RefreshStatistics(string userName, string rid)
        {
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            DAL_ProgramNavicat programNavicatDal = new DAL_ProgramNavicat();
            var configFileList = configFileDal.GetDeskStatistics();
            var desk = new
            {
                totalfilesnum = configFileList.TotalNum,
                processcfgfilesnum = configFileList.processCfgFilesNum,
                mlcfigfilenum = configFileList.MLCfigFileNum,
                modulecfgfilenum = configFileList.moduleCfgFileNum,
                todayaddfiles = configFileList.todayAddFiles
            };
            var navicats = programNavicatDal.GetProtramNavicatTree(userName, rid);
            var message = new { desk = desk, menus = navicats };
            var serializersettings = new JsonSerializerSettings
            {

                // 设置为驼峰命名

                ContractResolver = new CamelCasePropertyNamesContractResolver()

            };
            hubMessageServer.SendMessage(JsonConvert.SerializeObject(message, Newtonsoft.Json.Formatting.None, serializersettings));
        }

        /// <summary>
        /// 将目录信息存储到数据库
        /// </summary>
        private void SaveDirectoryInfoToDb(string fullPath,string parentPath,string folderName)
        {
            DAL_ConfigFile dAL_ConfigFile = new DAL_ConfigFile();

            // 获取导航功能ID
            DAL_ProgramNavicat navicat = new DAL_ProgramNavicat();
            var programid = navicat.GetProgramId(parentPath);
            // 现判断该文件是否存在
            string fileRelativePath = Path.Combine(parentPath, folderName).Replace("\\", @"/");
            int re= dAL_ConfigFile.ExistFile(fileRelativePath);
            if (re<=0)
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(fullPath);
                string currentId = System.Guid.NewGuid().ToString("N");
                ConfigFileInfoModel configFileInfo = new ConfigFileInfoModel();
                configFileInfo.currentId = currentId;
                configFileInfo.name = directoryInfo.Name;
                configFileInfo.ctype = "D";
                configFileInfo.path = fileRelativePath;
                configFileInfo.parentPath = parentPath;
                configFileInfo.fileSize = string.Empty;
                configFileInfo.updateTime = directoryInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                configFileInfo.createdTime = directoryInfo.CreationTime.ToString("yyyy-MM-dd HH:mm:ss");
                configFileInfo.programId = programid;
                configFileInfo.note = string.Empty;
                string parentId = dAL_ConfigFile.GetFileId(parentPath);
                configFileInfo.parentId = parentId;
                int parentLevel = dAL_ConfigFile.GetFileLevel(parentPath);
                configFileInfo.level = parentLevel+1;
                dAL_ConfigFile.AddConfigFile(configFileInfo);
            }



        }
    }
}
